package usf.vend.a.bull.db;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Environment;
import android.util.Log;

public class DBUpdater
{
	private String fileName = "db_version.txt";
	
	public void checkVersion()
	{
		try
		{
			URL url = new URL("http://rpobrien.myweb.usf.edu/Android/database/version.txt");
			HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
			urlCon.setRequestMethod("GET");
			urlCon.setDoOutput(true);
			urlCon.connect();
			
			String sdCard = Environment.getExternalStorageDirectory() + "/download/";
			File file = new File(sdCard);
			file.mkdirs();
			
			
			File outputFile = new File(file, fileName);
			FileOutputStream fOStream = new FileOutputStream(outputFile);
			InputStream iStream = urlCon.getInputStream();
			
			byte[] buffer = new byte[256];
			int bufLength = 0;
			while ((bufLength = iStream.read(buffer)) != -1)
			{
				fOStream.write(buffer, 0, bufLength);
			}
			
			fOStream.close();
			iStream.close();
			
			StringBuilder versionStr = new StringBuilder();
			BufferedReader reader = new BufferedReader(new FileReader(outputFile));
			String line;
			while ((line = reader.readLine()) != null)
			{
				versionStr.append(line);
			}
			Log.d("DBUpdater", versionStr.toString());
				
		}
		catch (IOException ex)
		{
			Log.d("DBUpdater", "Could not check version");
		}
	}
}
